package com.ricky.sms.controller;

import com.ricky.common_util.result.Result;
import com.ricky.sms.service.SmsService;
import com.ricky.sms.util.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
@Api(tags = "短信登录服务接口")
@RestController
@RequestMapping("api/sms")
public class MsgApiController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation(value = "发送验证码至手机")
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone){
        // 从redis中获取验证码，如果获取到，返回ok
        // key手机号 value验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //如果从redis取不到
        //生成验证码，通过整合服务短信进行发送
        code = RandomUtil.getSixBitRandom();
        boolean isSend = smsService.send(phone,code);
//        boolean isSend = true;
        //生成验证码放到redis中，设置有效时间
        if(isSend) {
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return Result.ok();
        }else{
            return Result.fail().message("发送短信失败，请稍后重试");
        }
    }
}
